
#include "CEventSystem.h"


CEventSystem* CEventSystem::GetInstance()
{
	static CEventSystem instance;
	return &instance;
}

void CEventSystem::RegisterClient(EVENT eventID, IListener* pClient)
{
	if(!pClient)
		return;
	m_mmDatabase.insert(make_pair(eventID, pClient));
}

void CEventSystem::UnregisterClient(EVENT eventID, IListener* pClient)
{
	pair<multimap<EVENT, IListener*>::iterator, multimap<EVENT, IListener*>::iterator> clients;

	clients = m_mmDatabase.equal_range(eventID);

	for(multimap<EVENT, IListener*>::iterator Iter = clients.first; Iter != clients.second; Iter++)
	{
		if((*Iter).second == pClient)
		{
			Iter = m_mmDatabase.erase(Iter);
			break;
		}
	}
}

void CEventSystem::DispatchEvent(CEvent* pEvent)
{
	pair<multimap<EVENT, IListener*>::iterator, multimap<EVENT, IListener*>::iterator> clients;

	clients = m_mmDatabase.equal_range(pEvent->GetEventID());

	for(multimap<EVENT, IListener*>::iterator Iter = clients.first; Iter != clients.second; Iter++)
	{
		(*Iter).second->HandleEvent(pEvent);
	}
}


void CEventSystem::SendEvent(EVENT eventID, void* pData)
{
	CEvent Event(eventID, pData);
	m_CurrentEvents.push_back(Event);
}

void CEventSystem::ProcessEvents()
{
	while(m_CurrentEvents.size())
	{
		DispatchEvent(&m_CurrentEvents.back());
		m_CurrentEvents.pop_back();
	}
}

void CEventSystem::ClearEvents()
{
	m_CurrentEvents.clear();
}

void CEventSystem::ShutdownEventSystem()
{
	m_mmDatabase.clear();
}